﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Utility.Web
{
    public class WebCookie
    {
        /// <summary>
        /// Get Cookie
        /// </summary>
        /// <param name="key">Cookie Name</param>
        /// <returns>Cookie value. If is null, return string.Empty</returns>
        public static string Get(string key)
        {
            if (HttpContext.Current.Request.Cookies[key] != null)
                return HttpContext.Current.Request.Cookies[key].Value;
            return string.Empty;
        }
        
        /// <summary>
        /// Create Cookie
        /// </summary>
        /// <param name="key">Cookie Name</param>
        /// <param name="value">Cookie Value</param>
        /// <param name="expireTime">if null: expireTime is 1 day</param>
        public static void Set(string key, string value, DateTime? expireTime)
        {
            HttpCookie nusCookie = new HttpCookie(key);
            nusCookie.Value = value;
            if (expireTime != null)
                nusCookie.Expires = (DateTime)expireTime;
            else
                nusCookie.Expires = DateTime.Now + new TimeSpan(24, 0, 0);//1 Day
            HttpContext.Current.Response.Cookies.Add(nusCookie);
        }

        /// <summary>
        /// Remove Cookie
        /// </summary>
        /// <param name="key">Cookie Name</param>
        public static void Remove(string key)
        {
            if(HttpContext.Current.Request.Cookies[key] != null)
                HttpContext.Current.Response.Cookies[key].Expires = DateTime.Now.AddDays(-1);
        }
    }
}
